//
//  SAPayCombinationVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/8/30.
//

#import "SAPayCombinationVC.h"
#import "UILabel+NSMutableAttributedString.h"

@interface SAPayCombinationVC ()<UITextFieldDelegate>

@property (nonatomic, strong) NSMutableDictionary *mdic;

@property (nonatomic, strong) UITextField *scanTf;
@property (nonatomic, strong) UITextField *cashTf;
@property (nonatomic, strong) UITextField *cardTf;
@property (nonatomic, strong) UITextField *weChatTf;
@property (nonatomic, strong) UITextField *AlipayTf;
@property (nonatomic, strong) UITextField *balanceTf;

@property (nonatomic, strong) UILabel *noCollectionLab;
@property (nonatomic, assign) double actualPrice;
@property (nonatomic, strong) NSMutableArray *tfMarr;

@end

@implementation SAPayCombinationVC

-(instancetype)initWithMdic:(NSMutableDictionary *)mdic {
    if (self = [super init]) {
        self.mdic = mdic;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

//防止多次结单
- (void)unisversalButtonAcrion:(UIButton *)sender
{
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(clickedSettlementBtn) object:sender];
    [self performSelector:@selector(clickedSettlementBtn) withObject:sender afterDelay:0.3f];
}

-(void)clickedSettlementBtn {
    
    CGFloat actualPrice = [self.mdic[@"actualPrice"] doubleValue] / 100;
    CGFloat totalPrice = [self.cashTf.text doubleValue] + [self.cardTf.text doubleValue] + [self.weChatTf.text doubleValue] + [self.AlipayTf.text doubleValue] + [self.balanceTf.text doubleValue] + [self.scanTf.text doubleValue];
    if (actualPrice > totalPrice) {
        [Prompt popPromptViewWithMsg:@"实付金额不足" duration:2];
        return;
    }
    
    NSMutableArray *payAddFormArray = [[NSMutableArray alloc] init];
    if (self.cashTf.text.length > 0) {
        NSMutableDictionary *payAddFormDic = [[NSMutableDictionary alloc] init];
        payAddFormDic[@"payType"] = @"1";
        payAddFormDic[@"payPrice"] = [NSString stringWithFormat:@"%0.f",[self.cashTf.text doubleValue] * 100];
        [payAddFormArray addObject:payAddFormDic];
    }
    
    if (self.cardTf.text.length > 0) {
        NSMutableDictionary *payAddFormDic = [[NSMutableDictionary alloc] init];
        payAddFormDic[@"payType"] = @"2";
        payAddFormDic[@"payPrice"] = [NSString stringWithFormat:@"%0.f",[self.cardTf.text doubleValue] * 100];
        [payAddFormArray addObject:payAddFormDic];
    }
    
    if (self.weChatTf.text.length > 0) {
        NSMutableDictionary *payAddFormDic = [[NSMutableDictionary alloc] init];
        payAddFormDic[@"payType"] = @"4";
        payAddFormDic[@"payPrice"] = [NSString stringWithFormat:@"%0.f",[self.weChatTf.text doubleValue] * 100];
        [payAddFormArray addObject:payAddFormDic];
    }
    
    if (self.AlipayTf.text.length > 0) {
        NSMutableDictionary *payAddFormDic = [[NSMutableDictionary alloc] init];
        payAddFormDic[@"payType"] = @"5";
        payAddFormDic[@"payPrice"] = [NSString stringWithFormat:@"%0.f",[self.AlipayTf.text doubleValue] * 100];
        [payAddFormArray addObject:payAddFormDic];
    }
    
    if (self.balanceTf.text.length > 0) {
        NSMutableDictionary *payAddFormDic = [[NSMutableDictionary alloc] init];
        payAddFormDic[@"payType"] = @"6";
        payAddFormDic[@"payPrice"] = [NSString stringWithFormat:@"%0.f",[self.balanceTf.text doubleValue] * 100];
        [payAddFormArray addObject:payAddFormDic];
    }
    
    if (self.scanTf.text.length > 0) {
        NSMutableDictionary *payAddFormDic = [[NSMutableDictionary alloc] init];
        payAddFormDic[@"payType"] = @"7";
        payAddFormDic[@"payPrice"] = [NSString stringWithFormat:@"%0.f",[self.scanTf.text doubleValue] * 100];
        [payAddFormArray addObject:payAddFormDic];
    }
    
    self.mdic[@"payForms"] = payAddFormArray;
    self.mdic[@"balancePrice"] = [NSString stringWithFormat:@"%0.f",(totalPrice - actualPrice) * 100];
    
    !self.settlementBlock ?: self.settlementBlock(self.mdic,payAddFormArray);
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0) {
        return YES;
    }
    if (textField.text.length == 0 && [self inputNum] > 1) {
        [Prompt popPromptViewWithMsg:@"最多只能选择2种支付方式" duration:2];
        return NO;
    }

    if((textField.text.length == 0) && [string isEqualToString:@"."]) {
        textField.text = @"0";
    }
    if([textField.text containsString:@"."]) {
        if ([string isEqualToString:@"."]) {
            return NO;
        }
        NSRange ran = [textField.text rangeOfString:@"."];
        if(range.location > ran.location) {
            if([textField.text pathExtension].length > 1) {
                return NO;
            }
        }
    }
    NSString *newStr = [NSString stringWithFormat:@"%@%@",textField.text,string];
    if (self.scanTf == textField) {
        if ([newStr doubleValue] >= 10000000) {
            return NO;
        }
    }
    if ([newStr doubleValue] >= 100000000){
        return NO;
    }
    if ([newStr doubleValue] > self.actualPrice) {
        return NO;
    }
    return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@".0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

-(NSInteger)inputNum {
    NSInteger index = 0;
    for (UITextField *tf in self.tfMarr) {
        if (tf.text.length > 0) {
            index++;
        }
    }
    return index;
}

- (void)textFieldEditChanged:(UITextField*)textField {
    double price = [textField.text doubleValue];
    if (price == self.actualPrice) {
        for (UITextField *tf in self.tfMarr) {
            if (tf != textField) {
                tf.text = @"";
            }
        }
    }else {
        UITextField *selectTf = nil;
        for (UITextField *tf in self.tfMarr) {
            if (tf != textField && tf.text.length > 0) {
                selectTf = tf;
            }
        }
        if (selectTf != nil) {
            selectTf.text = [NSString stringWithFormat:@"%0.2lf",self.actualPrice - price];
        }
    }
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"组合支付"];
    [self setBgImage:nil];
    
    self.view.backgroundColor = kBgColor;
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScaleNum(225))];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    self.actualPrice = [self.mdic[@"actualPrice"] doubleValue] / 100;
    UILabel *collectionLab = [[UILabel alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(StatusHeight), kScaleNum(300), kScaleNum(45))];
    collectionLab.text = [NSString stringWithFormat:@"收款金额 ￥%0.2f",self.actualPrice];
    collectionLab.font = kFont(15);
    collectionLab.textColor = kPinkColor;
    collectionLab.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:collectionLab];
    [collectionLab setAttributedStringWithSubString:@"收款金额" color:kBlackColor];
    
//    UILabel *noCollectionLab = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(170), kScaleNum(StatusHeight), kScaleNum(150), kScaleNum(45))];
//    noCollectionLab.text = @"未收金额  ￥0.00";
//    noCollectionLab.font = kFont(15);
//    noCollectionLab.textColor = kPinkColor;
//    noCollectionLab.textAlignment = NSTextAlignmentRight;
//    [self.view addSubview:noCollectionLab];
//    self.noCollectionLab = noCollectionLab;
//    [noCollectionLab setAttributedStringWithSubString:@"未收金额" color:kBlackColor];
    
//    BOOL isPayChannel = ![[SAValueManger shareInStance].userInfo.payChannel isEqualToString:@"2"];
//    if (isPayChannel == YES && scan == YES) {
//        self.isScan = YES;
//    }else {
//        self.isScan = NO;
//    }
    
    NSArray *imageArr = @[@"cash", @"card", @"weChat", @"Alipay"];
    NSArray *titleArr = @[@"  现金", @"  刷卡", @"  微信", @"  支付宝"];
    NSString *memberId = self.mdic[@"memberDataBean"][@"memberId"];
    NSString *scan = self.mdic[@"scan"];
    if (memberId && memberId.length > 0 && scan && scan.length > 0) {
        imageArr = @[@"pay_scan", @"cash", @"card", @"weChat", @"Alipay", @"balance"];
        titleArr = @[@"  扫码收款", @"  现金", @"  刷卡", @"  微信", @"  支付宝", @"  余额"];
        whiteView.height = kScaleNum(315);
    }else if (memberId && memberId.length > 0) {
        imageArr = @[@"cash", @"card", @"weChat", @"Alipay", @"balance"];
        titleArr = @[@"  现金", @"  刷卡", @"  微信", @"  支付宝", @"  余额"];
        whiteView.height = kScaleNum(270);
    }else if (scan && scan.length > 0) {
        imageArr = @[@"pay_scan", @"cash", @"card", @"weChat", @"Alipay"];
        titleArr = @[@"  扫码收款", @"  现金", @"  刷卡", @"  微信", @"  支付宝"];
        whiteView.height = kScaleNum(270);
    }
    
    self.tfMarr = [NSMutableArray array];
    for (int i = 0; i < imageArr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        [btn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        btn.titleLabel.font = kFont(15);
        btn.frame = CGRectMake(kScaleNum(20), kScaleNum(StatusHeight + 45) + i * kScaleNum(45), kScaleNum(120), kScaleNum(45));
        btn.contentHorizontalAlignment = 1;
        [self.view addSubview:btn];
        
        UITextField *inputTf = [[UITextField alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(230), kScaleNum(StatusHeight + 45) + i * kScaleNum(45), kScaleNum(210), kScaleNum(45))];
        inputTf.placeholder = @"输入金额";
        inputTf.font = kFont(15);
        inputTf.textAlignment = NSTextAlignmentRight;
        inputTf.textColor = kBlackColor;
        inputTf.delegate = self;
        inputTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        inputTf.keyboardType = UIKeyboardTypeDecimalPad;
        [inputTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        [self.view addSubview:inputTf];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(StatusHeight + 44.5) + i * kScaleNum(45), kScreenWidth - kScaleNum(40), kScaleNum(0.5))];
        line.backgroundColor = kBgColor;
        [self.view addSubview:line];
        
        if (i == 0) {
            inputTf.text = [NSString stringWithFormat:@"%0.2f",self.actualPrice];
        }
        if ([titleArr[i] isEqualToString:@"  扫码收款"]) {
            self.scanTf = inputTf;
        }else if ([titleArr[i] isEqualToString:@"  现金"]) {
            self.cashTf = inputTf;
        }else if ([titleArr[i] isEqualToString:@"  刷卡"]) {
            self.cardTf = inputTf;
        }else if ([titleArr[i] isEqualToString:@"  微信"]) {
            self.weChatTf = inputTf;
        }else if ([titleArr[i] isEqualToString:@"  支付宝"]) {
            self.AlipayTf = inputTf;
        }else if ([titleArr[i] isEqualToString:@"  余额"]) {
            self.balanceTf = inputTf;
        }
        [self.tfMarr addObject:inputTf];
    }
    
    UIButton *settlementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settlementBtn.frame = CGRectMake(kScaleNum(70), kScreenHeight - kScaleNum(50) - SafeFooterHeight, kScaleNum(235), kScaleNum(35));
    [settlementBtn setBackgroundImage:[UIImage imageNamed:@"button_blue_bg"] forState:UIControlStateNormal];
    [settlementBtn setTitle:@"结算" forState:UIControlStateNormal];
    settlementBtn.titleLabel.font = kBFont(16);
    [settlementBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [settlementBtn addTarget:self action:@selector(unisversalButtonAcrion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settlementBtn];
    
}

@end
